package com.hzy.api;

import com.hzy.common.R;
import com.hzy.service.ollama.OllamaVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 负责处理 /api/ollama/* 相关的 API 路由。
 */
public class OllamaApiVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(OllamaApiVerticle.class);

    // 提供一个静态方法来获取此 Verticle 的 Router，供主 HttpServerVerticle 挂载
    public static Router createRouter(Vertx vertx) {
        Router router = Router.router(vertx);

        // Ollama API 路由
        router.post("/generate").handler(context -> {
            JsonObject requestBody = context.body().asJsonObject();

            if (requestBody == null || !requestBody.containsKey("prompt") || !requestBody.containsKey("model")) {
                context.response()
                        .setStatusCode(400)

                        .end(new JsonObject().put("error", "Bad Request").put("details", "Required fields: 'model', 'prompt'.").encodePrettily());
                return;
            }

            // 通过 Event Bus 请求 OllamaVerticle
            vertx.eventBus().<String>request(OllamaVerticle.OLLAMA_REQUEST_ADDRESS, requestBody)
                    .onSuccess(ollamaReply -> {
                        context.response()
                                .end(R.success("操作成功", ollamaReply.body()).encodePrettily());
                    })
                    .onFailure(err -> {
                        LOGGER.error("Failed to get response from OllamaVerticle: {}", err.getMessage());
                        context.fail(err);
                    });
        });
        return router;
    }
}